using UnityEngine;
using System.Collections.Generic;

public class TrackGenerator : MonoBehaviour
{
    public GameObject trackSegmentPrefab; // 跑道段预制件
    public int initialSegments = 5; // 初始生成的跑道段数量
    public float segmentLength = 10f; // 每个跑道段的长度
    public float spawnAheadDistance = 20f; // 提前生成跑道的距离
    public int segmentsAheadToMaintain = 10; // 玩家前方需要保持的轨道段数量
    
    private Queue<GameObject> inactiveSegments = new Queue<GameObject>(); // 对象池，存储非活动的轨道段
    private Transform playerTransform;
    private float lastSpawnPosition = 0f;
    private bool isGeneratingNextSegment = false; // 标记是否正在生成下一段跑道
    
    void Start()
    {
        // 检查预制件是否已赋值
        if (trackSegmentPrefab == null)
        {
            Debug.LogError("Track segment prefab is NOT assigned in inspector!");
        }
        
        // 找到玩家对象
        playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
        
        // 如果没有找到玩家，使用默认位置
        if (playerTransform == null)
        {
            Debug.LogWarning("Player with tag 'Player' not found! Creating a reference object instead.");
            playerTransform = new GameObject("PlayerReference").transform;
        }
        
        // 生成初始跑道段
        Debug.Log("Generating initial " + initialSegments + " track segments");
        for (int i = 0; i < initialSegments; i++)
        {
            SpawnTrackSegment(i * segmentLength);
        }
        
        lastSpawnPosition = initialSegments * segmentLength;
        Debug.Log("Initial track generation completed. Last spawn position: " + lastSpawnPosition);
    }
    
    void Update()
    {
        // 确保玩家Transform有效
        if (playerTransform == null)
        {
            playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
            if (playerTransform == null)
            {
                Debug.LogWarning("Player transform is still null in Update()");
                return;
            }
        }
        
        // 检测玩家位置，确保前方有足够的轨道段
        EnsureEnoughSegmentsAhead();
        
        // 回收超出玩家后面的跑道段
        DespawnOldSegments();
    }
    
    void EnsureEnoughSegmentsAhead()
    {
        // 如果正在生成轨道段，则不再重复检测
        if (isGeneratingNextSegment)
        {
            return;
        }
        
        // 防止空引用
        if (playerTransform == null)
            return;
            
        // 计算需要生成的轨道段数量
        float playerZ = playerTransform.position.z;
        float maxDistance = playerZ + spawnAheadDistance;
        
        // 如果前方需要更多轨道段，则生成新的轨道段
        if (lastSpawnPosition < maxDistance)
        {
            isGeneratingNextSegment = true;
            
            // 计算需要生成多少个新的轨道段
            int segmentsToSpawn = Mathf.CeilToInt((maxDistance - lastSpawnPosition) / segmentLength);
            
            for (int i = 0; i < segmentsToSpawn; i++)
            {
                SpawnTrackSegment(lastSpawnPosition);
                lastSpawnPosition += segmentLength;
            }
            
            // 重置生成标记，以便下次检测
            Invoke("ResetGeneratingFlag", 0.1f);
        }
    }
    
    void ResetGeneratingFlag()
    {
        isGeneratingNextSegment = false;
    }
    
    void SpawnTrackSegment(float zPosition)
    {
        if (trackSegmentPrefab == null)
        {
            Debug.LogError("Track segment prefab is not assigned!");
            return;
        }
        
        Vector3 spawnPosition = new Vector3(0, 0, zPosition);
        GameObject newSegment;
        
        // 优先从对象池中获取轨道段
        if (inactiveSegments.Count > 0)
        {
            newSegment = inactiveSegments.Dequeue();
            newSegment.transform.position = spawnPosition;
            newSegment.transform.rotation = Quaternion.identity;
            newSegment.SetActive(true);
        }
        else
        {
            // 对象池为空时，创建新的轨道段
            newSegment = Instantiate(trackSegmentPrefab, spawnPosition, Quaternion.identity);
            newSegment.transform.parent = transform;
        }
    }
    
    void DespawnOldSegments()
    {
        // 确保玩家Transform有效
        if (playerTransform == null)
        {
            return;
        }
        
        // 移除超出玩家后面一定距离的跑道段
        float despawnThreshold = playerTransform.position.z -5f;
        
        // 遍历所有子对象（轨道段）
        foreach (Transform child in transform)
        {
            if (child == null)
                continue;
                
            GameObject segment = child.gameObject;
            if (segment.activeSelf && segment.transform.position.z < despawnThreshold)
            {
                // 将轨道段禁用并放回对象池
                segment.SetActive(false);
                inactiveSegments.Enqueue(segment);
            }
        }
    }
}